package com.guang.springbootrequestversion.resolver;

import com.guang.springbootrequestversion.bean.Cat;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义参数解析器:
 * 参考一：https://blog.csdn.net/xiexingshishu/article/details/123146760
 * 参考二：https://www.cnblogs.com/jere/p/15154126.html
 *
 * @author liguang
 * @date 2022/5/12 9:52
 */
public class BindHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 方法参数对象，可以获取得到任意方法的信息
     *
     * @param parameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() == Cat.class && parameter.hasParameterAnnotation(UserParam.class);
    }

    /**
     * supportsParameter返回true，那么如何来进行解析
     *
     * @param parameter
     * @param mavContainer
     * @param webRequest
     * @param binderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        // 获取得到原生的请求
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        int catAge = Integer.parseInt(age);
        Cat cat = new Cat();
        cat.setAge(catAge);
        cat.setName(name);
        return cat;
    }
}
